<template>
  <page-header-wrapper>
    <a-card :bordered='false'>
      <!--搜索区域-->
      <div class='table-page-search-wrapper'>
        <a-form layout='inline'>
          <a-row :gutter='48'>
            <a-col :md='8' :sm='24'>
              <a-form-item label='姓名'>
                <a-input v-model='queryParam.nickName' placeholder='请输入姓名或关键字' />
              </a-form-item>
            </a-col>
            <a-col :md='8' :sm='24'>
              <a-form-item label='录取状态'>
                <a-select v-model='queryParam.enrollStatus' placeholder='请选择' default-value='3'>
                  <a-select-option v-for='(item, index) in statusOptions' :key='index' :value='item.value'>
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <!--展开区域 => 高级搜索功能-->
            <template v-if='advanced'>
              <a-col :md='8' :sm='24'>
                <a-form-item label='总分'>
                  <a-input-number placeholder='请输入总分(大于)'
                                  :min='0'
                                  :max='150'
                                  v-model='queryParam.totalScore'
                                  style='width: 100%' />
                </a-form-item>
              </a-col>
              <a-col :md='8' :sm='24'>
                <a-form-item label='学号'>
                  <a-input-number v-model='queryParam.studentId' placeholder='请输入学号(支持模糊查询)'
                                  style='width: 100%' />
                </a-form-item>
              </a-col>
              <a-col :md='8' :sm='24'>
                <a-form-item label='账号状态'>
                  <a-select placeholder='请选择' default-value='0'>
                    <a-select-option value='0'>所有状态</a-select-option>
                    <a-select-option value='1'>正常</a-select-option>
                    <a-select-option value='2'>禁用</a-select-option>
                    <a-select-option value='3'>未知状态</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md='8' :sm='24'>
                <a-form-item label='更新日期'>
                  <!-- v-model='queryParam.updateTime'-->
                  <a-range-picker @change='addDataQueryParam' style='width: 100%' />
                </a-form-item>
              </a-col>
            </template>
            <a-col :md='!advanced && 8 || 24' :sm='24'>
              <span class='table-page-search-submitButtons'
                    :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type='primary' @click='searchNewcomer'>查询</a-button>
                <a-button style='margin-left: 8px' @click='() => this.queryParam = {}'>重置</a-button>
                <a @click='toggleAdvanced' style='margin-left: 8px'>
                  {{ advanced ? '收起' : '高级搜索' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
            <div style='margin-left: 30px;'>
              <a-space :size='20'>
                <a-button @click='exportExcel("newcomer")'>导出所有候选人名单</a-button>
                <a-button @click='exportExcel("scoreThrough")'>导出评分通过名单</a-button>
                <a-button @click='exportExcel("enrollThrough")'>导出录取通过名单</a-button>
              </a-space>
            </div>
          </a-row>
        </a-form>
      </div>
      <a-divider />
      <!--表格区域-->
      <a-table
        ref='table'
        size='default'
        rowKey='studentId'
        bordered
        :loading='tbLoading'
        :columns='columns'
        :data-source='loadData'
        :pagination='pagination'
        @change='handleTableChange'
        showPagination='auto'
      >
        <!--学号-->
        <span
          slot='studentId'
          style='cursor: pointer'
          @click='copy(studentId)'
          slot-scope='studentId'>
          {{ studentId }}
        </span>
        <!--姓名-->
        <span
          slot='nickName'
          style='cursor: pointer'
          @click='copy(nickName)'
          slot-scope='nickName'>
          {{ nickName }}
        </span>
        <!--分数-->
        <span
          slot='totalScore'
          slot-scope='totalScore'>
          {{ totalScore }}
        </span>
        <!--录取状态-->
        <span
          slot='enrollStatus'
          slot-scope='enrollStatus'>
          <a-badge
            :status='enrollStatus | statusTypeFilter'
            :text='enrollStatus | statusFilter' />
        </span>
        <!--修改时间-->
        <span
          slot-scope='updateTime'
          slot='updateTime'>
          {{ updateTime || '未提交' }}
        </span>
        <!--操作-->
        <span
          slot='action'
          slot-scope='text, record'>
          <template>
            <a @click='handleEdit(record)'>修改</a>
            <span v-if='record.status !== 2'>
              <a-divider type='vertical' />
              <a @click='handleEnroll(record)'>一键录取</a>
            </span>
          </template>
        </span>
      </a-table>
      
      <!--修改弹层-->
      <a-modal
        title='学生信息'
        :visible='showFormDialog'
        :confirm-loading='confirmLoading'
        @ok='handleSubmit'
        okText='确认修改'
        cancelText='取消修改'
        @cancel='showFormDialog = false'
      >
        
        <a-form ref='elForm'
                :form='form'
                :labelAlign="'left'"
                okText='确认'
                cancel-text='取消'
                @submit='handleSubmit'
                :label-col='{ span: 4 }' :wrapper-col='{ span: 15 }'>
          
          <a-form-item label='用户ID'>
            <a-input
              v-decorator="['userId',{initialValue: tempForm.userId}]"
              :style="{width: '120%'}"
              :disabled='true'>
            </a-input>
          </a-form-item>
          
          <a-form-item label='学号'>
            <a-input
              v-decorator="['studentId',{initialValue: tempForm.studentId}]"
              :style="{width: '120%'}"
              :disabled='true'>
            </a-input>
          </a-form-item>
          
          <a-form-item label='姓名'>
            <a-input
              v-decorator="['nickName', { rules: [{ required: true, message: '姓名不能为空' }], initialValue: tempForm.nickName }]"
              placeholder='请输入学生姓名'
              :style="{width: '120%'}">
            </a-input>
          </a-form-item>
          
          <a-form-item label='分数'>
            <a-input-number
              :min='0'
              :max='100'
              :style="{width: '120%'}"
              value='未进行答题'
              :disabled='true'>
            </a-input-number>
          </a-form-item>
          
          <a-form-item label='班级'>
            <a-input placeholder='请输入学生班级'
                     v-decorator="['clasz', { rules: [{ required: true, message: '班级不能为空' }], initialValue: tempForm.clasz }]"
                     :style="{width: '120%'}">
            </a-input>
          </a-form-item>
          
          <a-form-item label='手机号码'>
            <a-input
              v-decorator="['phonenumber', { rules: [{ required: true, message: '手机号码不能为空' }],  initialValue: tempForm.phonenumber }]"
              placeholder='请输入手机号码'
              :style="{width: '120%'}">
            </a-input>
          </a-form-item>
          
          <a-form-item label='录取状态'>
            <a-select
              dafult-value='0'
              v-decorator="['enrollStatus', { rules: [{ required: true, message: '录取状态不能为空' }], initialValue: tempForm.enrollStatus || '未知状态' }]"
              placeholder='请选择下拉选择'
              :style="{width: '120%'}">
              <a-select-option v-for='(item, index) in statusOptions' :key='index' :value='item.value'
                               :disabled='item.disabled'>{{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          
          <a-form-item label='邮箱'>
            <a-input placeholder='请输入学生邮箱'
                     :style="{width: '120%'}"
                     v-decorator="['email', { rules: [{ required: true, message: '邮箱不能为空' }], initialValue: tempForm.email }]">
            </a-input>
          </a-form-item>
          
          <a-form-item label='性别'>
            <a-select
              dafult-value='1'
              v-decorator="['gender', { rules: [{ required: true, message: '性别不能为空' }], initialValue: tempForm.sex === '1' ?'男' :'女' }]"
              placeholder='请选择下拉选择'
              :style="{width: '120%'}">
              <a-select-option :value='1'>
                男
              </a-select-option>
              <a-select-option :value='0'>
                女
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      
      </a-modal>
      
      <!-- 确认一键录取 -->
      <a-modal
        :centered='true'
        :maskClosable='false'
        :closable='false'
        title='确认录取'
        :visible='showEnroll'
        :confirm-loading='confirmLoadingEnroll'
        @ok='sureEnroll'
        @cancel='enrollCancel'
      >
        
        <a-descriptions :title="currentStudent.name + '的信息'" bordered>
          <a-descriptions-item label='学号'>
            {{ currentStudent.studentId }}
          </a-descriptions-item>
          
          <a-descriptions-item label='录取状态' :span='3'>
            <a-badge status='1' text='进行中' />
          </a-descriptions-item>
        </a-descriptions>
      
      
      </a-modal>
    
    
    </a-card>
  </page-header-wrapper>
</template>

<script>
import FormModelDialog from '@/views/list/components/FormModelDialog.vue'
import { getNewcomerByUserId, getNewcomerList, onekeyEnroll, updateNewcomer } from '@/api/newcomer'
import axios from 'axios'

const columns = [
  {
    title: '学号',
    width: 200,
    dataIndex: 'studentId',
    scopedSlots: { customRender: 'studentId' }
  },
  {
    title: '姓名',
    dataIndex: 'nickName',
    scopedSlots: { customRender: 'nickName' }
  },
  {
    title: '班级',
    dataIndex: 'clasz',
    scopedSlots: { customRender: 'clasz' }
  },
  {
    title: '分数',
    dataIndex: 'totalScore',
    sorter: (a, b) => a.totalScore - b.totalScore,
    needTotal: true,
    customRender: function(text) {
      if (text * 1 <= -1 || text === undefined || text === null) {
        text = '未进行答题'
        return text
      } else {
        return text + ' 分'
      }
    }
  },
  {
    title: '录取状态',
    dataIndex: 'enrollStatus',
    scopedSlots: { customRender: 'enrollStatus' },
    sorter: (a, b) => a.enrollStatus - b.enrollStatus
  },
  {
    title: '提交题目时间',
    dataIndex: 'updateTime',
    sorter: true,
    customRender: function(updateTime) {
      if (updateTime === '' || updateTime === undefined || updateTime === null) {
        updateTime = '未进行答题'
        return updateTime
      } else {
        return updateTime
      }
    }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]

const statusMap = {
  0: {
    status: 'processing',
    text: '进行中'
  },
  1: {
    status: 'error',
    text: '未录取'
  },
  2: {
    status: 'success',
    text: '已录取'
  }
}

const statusOptions = [
  {
    'label': '进行中',
    'value': '0'
  },
  {
    'label': '未录取',
    'value': '1'
  },
  {
    'label': '已录取',
    'value': '2'
  }
]
import { exportExcel } from '@/api/common'
import FileSaver from 'file-saver'
import { formattedDate } from '@/utils/util'

export default {
  name: 'TableList',
  components: {
    FormModelDialog
  },
  data() {
    return {
      // 创建表单
      columns,
      form: this.$form.createForm(this, { name: 'newcomerInfo' }),
      tempForm: {},
      statusOptions,
      showFormDialog: false, // 是否展示修改的表单模型
      confirmLoading: false, // 按钮加载效果
      tbLoading: true, // 表格加载效果
      // 录取信息
      currentStudent: {
        userId: '',
        studentId: '',
        nickName: ''
      },
      // 展示录取框
      showEnroll: false,
      confirmLoadingEnroll: false,
      
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表格数据
      loadData: [],
      
      // 日期范围
      dateRange: [],
      
      //分页参数
      pagination: {
        size: 'large',
        current: 1,
        pageSize: 10,
        total: 0,
        pageSizeOptions: ['10', '15', '20'],//可选的页面显示条数
        showTotal: (total, range) => {
          return ' 共' + total + '条'
        }, //展示每页第几条至第几条和总数
        hideOnSinglePage: false, // 只有一页时是否隐藏分页器
        showQuickJumper: true, //是否可以快速跳转至某页
        showSizeChanger: true //是否可以改变pageSize
      }
    }
  },
  filters: {
    statusFilter(type) {
      return statusMap[type].text
    },
    statusTypeFilter(type) {
      return statusMap[type].status
    }
  },
  created() {
    this.searchNewcomer()
  },
  methods: {
    // 搜索新人
    searchNewcomer() {
      getNewcomerList(this.queryParam).then((res) => {
        this.loadData = res.rows
        this.pagination.total = res.total
        this.tbLoading = false
      })
    },
    
    //表格改变时触发
    handleTableChange(pagination, filters, sorter) {
      this.pagination = pagination
      // 添加分页参数
      this.queryParam.pageNum = pagination.current
      this.queryParam.pageSize = pagination.pageSize
      
      this.searchNewcomer()
    },
    
    // 编辑学生信息
    handleEdit(record) {
      // 显示弹层
      this.showFormDialog = true
      // 发送请求获取学生信息
      getNewcomerByUserId(record.userId).then(response => {
        this.tempForm = response.data
      })
    },
    
    // 一键录取
    handleEnroll(record) {
      this.currentStudent.studentId = record.studentId
      this.currentStudent.name = record.nickName
      this.currentStudent.userId = record.userId
      this.showEnroll = true
    },
    
    // 展开高级搜索功能
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    
    // 添加时间参数
    addDataQueryParam(date, dataList) {
      this.dateRange = dataList
    },
    
    // 重置搜索表单
    resetSearchForm() {
      this.queryParam = {}
    },
    
    // 确认录取学生
    sureEnroll() {
      // 发送请求...
      this.confirmLoadingEnroll = true
      onekeyEnroll(this.currentStudent.userId).then(response => {
        this.$notification.open({
          message: '录取成功',
          description:
            `${this.currentStudent.studentId + '  ' + this.currentStudent.nickName} 录取成功`,
          icon: <a-icon type='smile' style='color: #108ee9' />
        })
        this.resetEnroll()
        this.searchNewcomer()
        this.confirmLoadingEnroll = false
      })
    },
    
    // 取消录取学生
    enrollCancel() {
      this.resetEnroll()
    },
    
    // 重置当前选中录取学生的信息
    resetEnroll() {
      this.showEnroll = false
      this.currentStudent = {}
    },
    
    // 提交表单
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          updateNewcomer(values).then(() => {
            this.$message.success('更新成功')
            this.showFormDialog = false
            // 重置表单
            this.form.resetFields()
            this.searchNewcomer()
          })
        }
      })
    },
    
    // 导出excel数据
    exportExcel(type) {
      let fileName = ''
      if (type === 'newcomer') {
        fileName = '获选人名单'
      } else if (type === 'scoreThrough') {
        fileName = '评分通过名单'
      } else if (type === 'enrollThrough') {
        fileName = '录取通过名单'
      }
      exportExcel(type)
        .then(res => {
          let blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
          FileSaver.saveAs(blob, '至' + formattedDate(new Date(Date.now())) + fileName + '.xlsx')
          this.$message.success('导出成功')
        })
    },
    
    copy(copyResult) {
      //创建input标签
      var input = document.createElement('input')
      //将input的值设置为需要复制的内容
      input.value = copyResult
      //添加input标签
      document.body.appendChild(input)
      //选中input标签
      input.select()
      //执行复制
      document.execCommand('copy')
      //成功提示信息
      this.$message.success('复制成功')
      //移除input标签
      document.body.removeChild(input)
    }
  }
}
</script>
<style scoped>
a-row {
  display: flex;
}

a-col {
  display: flex;
  align-items: center;
}
</style>